<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/18
 * Time: 18:22
 */

namespace app\index\controller;
use think\Request;
use think\Exception;
use think\Db;
use think\Cache;
use app\common\trilateral\wxBizDataCrypt;
use app\console\model\Member;
class WeChat
{
    // 微信登录
    public function obtain()
    {
        // 获取参数
        $data = Request::instance()->param();
        writeLog(json_decode($data));
        if (empty($data['token']) || empty($data['openid'])) throw new Exception('not Empty');

        // 解析微信
        $arr = json_decode(file_get_contents('https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['token'] . '&openid=' . $data['openid']), true);
        writeLog(json_decode('arr'.$arr));
        // halt($arr);

        if (empty($arr['openid'])) return ['code' => 400, 'message' => '解析失败'];

        // 读取是否存在
        $id = Db::name('member')->where(['unionid' => $arr['unionid']])->value('id');

        // 如果不存在
        if (empty($id)) {

            return ['code' => 403, 'message' => '用户未注册', 'unionid' => $arr['unionid'], 'headimgurl' => $arr['headimgurl'], 'nickname' => $arr['nickname'], 'sex' => $arr['sex']];

        }

        return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $id,]];

        // // 启动事务
        // Db::startTrans();
        //
        // try {
        //
        //     $user_id = Db::name('member')->insertGetId([
        //         'wechat_id'   => $arr['unionid'],
        //         'avatar'      => $arr['headimgurl'],
        //         'nickname'    => str_replace("馃挀", "", $arr['nickname']),
        //         'sex'         => $arr['sex'],
        //         'create_ip'   => getIP(),
        //         'create_time' => time(),
        //     ]);
        //
        //
        //     // 提交事务
        //     Db::commit();
        //
        //     return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $user_id]];
        //
        // } catch (\Exception $e) {
        //
        //     // 回滚事务
        //     Db::rollback();
        //
        //     return ['code' => 401, 'message' => '网络繁忙'];
        // }

        // }

    }

    /**
     * 苹果登录
     */
    public function apple_login(){
        $param = Request::instance()->param();
        $id = Member::where(['apple_id' => $param['apple_id']])->value('id');

        // 如果不存在
        if (empty($id)) {
            return (['code' => 403, 'message' => '用户未注册','apple_id' => $param['apple_id']]);
        }
        return (['code' => 200, 'message' => '成功', 'user_id' => $id]);
    }

    public function apple_register()
    {
        Db::startTrans();
        try {
            $param = Request::instance()->param();
//            halt($param);
            if (Cache::get('sms_verify_' . 'apple_register_' . $param['username']) != $param['captcha']) {
                return (['code' => 400, 'message' => '验证码不正确']); //这里没有验证手机号是否绑定过 如果绑定过别的微信又绑定了这个也不可能
            }

//            dump($param['password']);
            $password = ($param['password']);

            $find = Member::where('username', $param['username'])->find();

            $data = [
                'apple_id' => $param['apple_id'],
                //'head_pic' => $this->downloadUrlImage($param['headimgurl'],'./uploads/member/',microtime(true)),
                'nickname' => '苹果用户'. $rand = mt_rand(1000,9999),
                //                'sex'         => $param['sex'],
                'create_ip' => getIP(),
                'create_time' => date('Y-m-d H:i:s', time()),
                'username' => $param['username'],
                'password' => sha1($password),
            ];

            if (!empty($find)) { //修改绑定手机号
                Member::where('id', $find['id'])->update($data);
                Db::commit();
                return (['code' => 200, 'message' => '绑定成功', 'user_id' => $find['id']]);
            } else { //注册

                $ret = Db::name('Member')->insertGetId($data);

                Db::commit();
                return (['code' => 200, 'message' => '注册', 'user_id' => $ret]);
            }

        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    function random_str($length=10)
    {
        //生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
        $arr = array_merge(range(0, 9), range('A', 'Z'));

        $str = '';
        $arr_len = count($arr);
        for ($i = 0; $i < $length; $i++)
        {
            $rand = mt_rand(0, $arr_len-1);
            $str.=$arr[$rand];
        }

        return $str;
    }


    public function obtain_zhuce1()
    {
        $data = Request::instance()->param();
        writeLog('ijson-'.json_encode($data));
        if (!$data['unionid'] || !$data['tel'] || !$data['password']) return ['code' => 403, 'message' => '参数错误'];

        $tel = Db::name('member')->where('username', $data['tel'])->value('id');
        $name = date('Ymd') . DS . md5(microtime(true)) . ".jpg";
        $path = "./uploads/";
        $map = "/uploads/" . $name;
        put_file_from_url_content($data['headimgurl'], $name, $path);
        if (!$tel) {


            // 启动事务
            Db::startTrans();

            try {
                $user_id = Db::name('member')->insertGetId([
                    'wechat_id'   => $data['unionid'],
                    'avatar'      => $map,
                    'nickname'    => str_replace("馃挀", "", $data['nickname']),
                    'sex'         => $data['sex'],
                    'create_ip'   => getIP(),
                    'create_time' => date('Y-m-d H:i:s',time()),
                    'username'    => $data['tel'],
                    'password'    => sha1($data['password']),
                ]);

                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $user_id]];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 402, 'message' => $e->getMessage()];
            }
        }else{
            $adf = Db::name('member')->where('username',$data['tel'])->update([
                'wechat_id'   => $data['unionid'],
                'avatar'      => $map,
                'nickname'    => str_replace("馃挀", "", $data['nickname']),
                'sex'         => $data['sex'],
                'create_ip'   => getIP(),
                'create_time' => date('Y-m-d H:i:s',time()),
                'password'    => sha1($data['password']),
            ]);
            writeLog('json'.json_encode($adf));
            $user_id = Db::name('member')->where('username',$data['tel'])->value('id');
            if($adf) return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $user_id]];
            if(!$adf) return ['code' => 401, 'message' => '注册失败'];
        }


    }

    public function obtain_xiao()
    {
        $appid = 'wx2bcc6a6ed1bbdb7e';
        $secret = 'f3286548a553d58726d4c13d8c2b47f2';
        $param = Request::instance()->param();
        writeLogOrder('param:'.json_encode($param));
        $item=json_decode(file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code=".$param['code']."&grant_type=authorization_code"));
        writeLogOrder('$item:'.json_encode($item));
////        $appid = 'wxfad7142a43ba4835';
        $sessionKey = $item->session_key;
////66666666666666
        $encryptedData=$param['encryptedData'];
//
        $iv = $param['iv'];
//
       $pc = new WXBizDataCrypt($appid, $sessionKey);
//
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        writeLogOrder('$data:'.($data));
       $arr = json_decode($data);
//        writeLogOrder('item:'.json_encode($item));
//        $access_token = json_decode(file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}"));
//        writeLogOrder('$access_token:'.json_encode($access_token));
//        $arr = json_decode(file_get_contents('https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token->access_token . '&openid=' . $item->openid), true);
////        dump($data);
//        writeLogOrder('$arr:'.json_encode($arr));
        $id = Db::name('member')->where(['wechat_id' => $arr->unionId])->value('id');
        if (empty($id)) {
            return ['code' => 403, 'message' => '用户未注册', 'unionid' => $arr->unionId,'openid' => $arr->openId,'nickName' => $arr->nickName,'gender' => $arr->gender,'avatarUrl' => $arr->avatarUrl];
        }

        return ['code' => 200, 'message' => '成功', 'user_id' => $id,'openid' => $arr->openId,'unionid' => $arr->unionId];

    }

    public function openid()
    {
        $appid = 'wx2bcc6a6ed1bbdb7e';
        $secret = 'f3286548a553d58726d4c13d8c2b47f2';
        $param = Request::instance()->param();
        writeLogOrder('param:'.json_encode($param));
        $item=json_decode(file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code=".$param['code']."&grant_type=authorization_code"));
//        writeLogOrder('$item:'.json_encode($item));
//////        $appid = 'wxfad7142a43ba4835';
//        $sessionKey = $item->session_key;
//////66666666666666
//        $encryptedData=$param['encryptedData'];
////
//        $iv = $param['iv'];
////
//        $pc = new WXBizDataCrypt($appid, $sessionKey);
////
//        $errCode = $pc->decryptData($encryptedData, $iv, $data);
//        writeLogOrder('$data:'.($data));
//        $arr = json_decode($data);
        $arr = $item;
        return ['code' => 200, 'message' => '获得openid','openid' => $arr->openid];

    }


    public function t()
    {
        $arr = json_decode(file_get_contents('https://api.weixin.qq.com/sns/userinfo?access_token=22_0jkq8tf0-yzSHf6FfHZJCF4zagkXBtoq-C3FH956P0T6wHba1iNRSOPsgBOS6rc0cxAMyPWyznNan7wcNpwq6rauKHvm7V13I9YaMsc5P61xurVmAgs-0oY7nW_kVOtxCUv-4XYelsBFLQnPYAYfAFAHJH&openid=oGzK-4t5ARLKePMosVxTSN3HLVTg'), true);
        halt($arr);
    }

    public function obtain_zhuce()
    {
        $data = Request::instance()->param();
        $smsVerify = Cache::get('sms_verify_bind_tel_' . $data['tel']);
        if ($smsVerify != $data['code']) {
            return ['code' => 401, 'message' => '验证码错误'];
        }
        writeLog('ijson-'.json_encode($data));
        if (!$data['unionid'] || !$data['tel'] || !$data['password'] || !$data['code']) return ['code' => 403, 'message' => '参数错误'];

        $tel = Db::name('member')->where('username', $data['tel'])->value('id');
        $name = date('Ymd') . DS . md5(microtime(true)) . ".jpg";
        $path = "./uploads/";
        $map = "/uploads/" . $name;
        put_file_from_url_content($data['headimgurl'], $name, $path);
        if (!$tel) {
            // 启动事务
            Db::startTrans();
            try {
                $user_id = Db::name('member')->insertGetId([
                    'wechat_id'   => $data['unionid'],
                    'avatar'      => $map,
                    'nickname'    => str_replace("馃挀", "", $data['nickname']),
                    'sex'         => $data['sex'],
                    'create_ip'   => getIP(),
                    'create_time' => date('Y-m-d H:i:s',time()),
                    'username'    => $data['tel'],
                    'password'    => sha1($data['password']),
                ]);
                Db::name('member_distribution')->insert(['distribution_id' => '0', 'referrals_id' => $user_id, 'hierarchy' => '0,', 'level' => '1', 'create_time' => date('Y-m-d H:i:s', time())]);
                (new \app\index\controller\Coupon())->send(3,$user_id);
                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '成功', 'user_id' => $user_id];


            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 402, 'message' => $e->getMessage()];
            }
        }else{
            $adf = Db::name('member')->where('username',$data['tel'])->update([
                'wechat_id'   => $data['unionid'],
                'avatar'      => $map,
                'nickname'    => str_replace("馃挀", "", $data['nickname']),
                'sex'         => $data['sex'],
                'create_ip'   => getIP(),
                'create_time' => date('Y-m-d H:i:s',time()),
                'password'    => sha1($data['password']),
            ]);
            writeLog('json'.json_encode($adf));
            $user_id = Db::name('member')->where('username',$data['tel'])->value('id');
            if($adf) return ['code' => 200, 'message' => '成功', 'user_id' => $user_id];
            if(!$adf) return ['code' => 401, 'message' => '注册失败'];
        }


    }
}